package com.fingerth.crawler.room

import com.fingerth.crawler.App
import com.fingerth.crawler.bean.NovelListBean

class NovelCollectionDaoUtils {

//    val pageSize = 30

    private val dao: NovelCollectionDao? by lazy { App.app.roomNovel?.novelCollectionDao() }

    fun insert(nBean: NovelListBean): Int {
        var repeatSize = 0
        nBean.data.data.let { d ->
            d.forEach {
                val h = queryById(it.fictionId)
                if (h == null) dao?.insert(NovelCollection(it)) else {
                    val isChange = h.change(it)
                    if (isChange) dao?.update(h) else repeatSize++
                }
            }
        }
        return repeatSize
    }

//    fun insert(history: NovelCollection) {
//        val h = queryById(history.fictionId)
//        if (h == null) dao?.insert(history)
//        EventBus.getDefault().post(BrowseNovelHistoryChangeEvent())
//    }

//    fun insert2(history: NovelCollection) {
//        dao?.insert(history)
//        EventBus.getDefault().post(BrowseNovelHistoryChangeEvent())
//    }
//
//    fun update(fictionId: String, chapterId: String) {
//        queryById(fictionId)?.let {
//            it.chapterId = chapterId
//            it.lastTime = Date().time
//            novelHistoryDao?.update(it)
//        }
//        EventBus.getDefault().post(BrowseNovelHistoryChangeEvent())
//    }

    fun count(): Int = dao?.count() ?: 0
    fun countByType(type: String): Int = dao?.countByType(type) ?: 0


    fun queryByIndex(index: Int): NovelCollection? = dao?.queryByIndex(index)
//    fun queryHistory(index: Int): Array<NovelCollection> = dao?.queryHistory((index - 1) * pageSize, pageSize) ?: arrayOf()

    fun queryById(fictionId: String): NovelCollection? = dao?.queryById(fictionId)


}